package cn.netbox.spring.handler;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * description:
 * date: 2021/12/4 19:16
 * author: Alex
 * version: 1.0
 */
@Aspect
@Component
public class MyAspect {

    @Before("execution(* *cn.netbox.spring.service.impl.MyServiceImpl.methodA(..))")
    public void myBefore() {
        System.out.println("当前时间:" + new Date());
    }

    @Before("execution(* *cn.netbox.spring.service.impl.MyServiceImpl.methodA(..))")
    public void myBefore1(JoinPoint joinPoint) {
        // 获取签名
        System.out.println(joinPoint.getSignature().getName());
        // 获得参数
        for (Object arg : joinPoint.getArgs()) {
            System.out.println(arg);
        }
    }

    @AfterReturning(value = "execution(* cn.netbox.spring.service.impl.MyServiceImpl.methodB())",
            returning = "returns")
    public Object myAfterRuturning(Object returns) {
        System.out.println("执行方法之后返回值" + returns);
        return returns;
    }

    @Around("execution(* cn.netbox.spring.service.impl.MyServiceImpl.methodC(..))")
    public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("执行环绕通知A");
        System.out.println( proceedingJoinPoint.getSignature());
        // method.invoke()
        System.out.println("执行环绕通知B");
        return proceedingJoinPoint.proceed();
    }

    /**
     * try{
     *     目标代码
     * }catch(Exception e) {
     *     e.....
     * }
     * @param exception
     */
    @AfterThrowing(value = "myPoint()",throwing = "exception")
    public void myAfterThrowing(Exception exception) {
        System.out.println("抛出异常"+exception.getMessage());
    }

    /**
     * finally{
     *  最终通知的代码
     * }
     */
    @After(value = "myPoint()")
    public void myAfter(JoinPoint joinPoint) {
        for (Object arg : joinPoint.getArgs()) {
            System.out.println(arg);
        }
        System.out.println("下课吃饭");
    }

    @Pointcut("execution(* cn.netbox.spring.service.impl.MyServiceImpl.methodD(..))")
    public void myPoint() {
        // 不用写代码
    }
}
